import type { ConfigProviderThemeVars } from 'wot-design-uni';
import { useThemeStore } from '@/store';
import { storeToRefs } from 'pinia';

export function useTheme(vars?: ConfigProviderThemeVars) {
  const store = useThemeStore();
  const { followSystem, theme, themeVars, colors } = storeToRefs(store);
  const setThemeColor = store.setThemeColor;
  /* 替换 Wot 组件的样式 */
  vars && (themeVars.value = vars);

  const setTheme = () => {
    nextTick(() => {
      if (followSystem.value) {
        // #ifdef APP-PLUS
        plus.nativeUI.setUIStyle('auto'); // 设置应用主题为跟随系统（android下能够切换，IOS 未测试）
        theme.value = 'light';
        // #endif
        // #ifndef APP-PLUS
        uni.getSystemInfo({
          success: (res: any) => {
            const osThemeInfo = res.hostTheme ? res.hostTheme : res.osTheme;
            theme.value = osThemeInfo;
            uni.setNavigationBarColor({
              frontColor: theme.value === 'light' ? '#000000' : '#ffffff',
              backgroundColor: theme.value === 'light' ? '#ffffff' : '#000000'
            });
            // 设置 tabBar 样式
            uni.setTabBarStyle({
              color: theme.value === 'light' ? '#64748b' : '#9ca3af',
              selectedColor: '#667eea',
              backgroundColor: theme.value === 'light' ? '#ffffff' : '#000000',
              borderStyle: theme.value === 'light' ? 'white' : 'black'
            });
          }
        });
        // #endif
      } else {
        // #ifdef APP-PLUS
        plus.nativeUI.setUIStyle('light'); // 设置应用主题为跟随系统（android下能够切换，IOS 未测试）
        // #endif
        uni.setNavigationBarColor({
          frontColor: theme.value === 'light' ? '#000000' : '#ffffff',
          backgroundColor: theme.value === 'light' ? '#ffffff' : '#000000'
        });
        // 设置 tabBar 样式
        uni.setTabBarStyle({
          color: theme.value === 'light' ? '#64748b' : '#9ca3af',
          selectedColor: '#667eea',
          backgroundColor: theme.value === 'light' ? '#ffffff' : '#000000',
          borderStyle: theme.value === 'light' ? 'white' : 'black'
        });
      }
    });
  };

  watch(theme, () => {
    setTheme();
  });

  onShow(() => {
    setTheme();
  });

  return {
    theme,
    themeVars,
    setTheme,
    setThemeColor,
    colors
  };
}
